//
//  KYBadgeButton.swift
//  NormalHE
//
//  Created by SHANGLU on 16/12/29.
//  Copyright © 2016年 heky. All rights reserved.
//

import UIKit

class KYBadgeButton: UIButton {

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */
    
    var badgeValue:String?{
    
        willSet{
        
            if newValue != nil && Int(newValue!)! > 0{
                self.hidden = false
                
                var frame = self.frame
                let badgeH = self.currentBackgroundImage?.size.height
                var badgeW = self.currentBackgroundImage?.size.width
                if newValue!.characters.count > 0 {
                
                    let font = self.titleLabel!.font
                    let dict = [
                        NSFontAttributeName:font
                    ]
                    
                    let badgeSize = (newValue! as NSString).boundingRectWithSize(CGSize(width: 9999,height: 9999), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: dict, context: nil).size
                    badgeW = badgeSize.width + 10
                }
                frame.size.width = badgeW!
                frame.size.height = badgeH!
                frame.origin.x = 0
                frame.origin.y = 0
                self.frame = frame
                
            }else{
                self.hidden = true
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.setBackgroundImage(UIImage(named:"main_badge_os7"), forState: .Normal)
        self.titleLabel?.font = UIFont.systemFontOfSize(11)
        self.userInteractionEnabled = false
        
    }
    
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
